package com.zeyi.chat.utils;

import com.zeyi.chat.handler.Dispatcher;
import com.zeyi.chat.dto.Message;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @author zeyi
 */
public class SocketUtil {
    private static final String ip = "127.0.0.1";
    private static final int port = 9001;
    private static Socket socket;

    public static Socket getSocket() {
        return socket;
    }

    private static void connect() {
        try {
            socket = new Socket(ip, port);
            Dispatcher dispatcher = new Dispatcher(socket);
            dispatcher.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void send(Message message) {
        if (socket == null) {
            connect();
        }
        try {
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
